<script setup>
import { ref, watch, onMounted } from 'vue'

const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const age = ref('')
const sex = ref('男')
const phone = ref('')
const role = ref('用户')
console.log('初始角色值:', role.value);
const enterpriseCode = ref('')
const errorMessage = ref('');
  const passwordErrorMessage = ref('')

watch(role, (newValue, oldValue) => {
  console.log('角色变化: 旧值=', oldValue, '新值=', newValue, '类型=', typeof newValue);
  console.log('企业编码显示状态:', ['管理员', '授权医护人员', '健康管理师'].includes(newValue));
})

onMounted(() => {
  console.log('组件挂载时角色值:', role.value, '类型:', typeof role.value);
})

const validatePassword = () => {
    if (password.value && !/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password.value)) {
      passwordErrorMessage.value = '密码必须包含大小写字母和数字且不小于6位';
    } else {
      passwordErrorMessage.value = '';
    }
  };

  const handleRegister = async () => {
  console.log('当前角色:', role.value);
  console.log('是否显示企业编码:', ['管理员', '授权医护人员', '健康管理师'].includes(role.value));
  // 非空检查
  if (!username.value.trim()) {
    errorMessage.value = '用户名不能为空';
    return;
  }
  if (!password.value.trim()) {
    errorMessage.value = '密码不能为空';
    return;
  }
  // 检查密码验证错误
  if (passwordErrorMessage.value) {
    errorMessage.value = passwordErrorMessage.value;
    return;
  }
  if (!confirmPassword.value.trim()) {
    errorMessage.value = '请确认密码';
    return;
  }
  if (!age.value.trim()) {
    errorMessage.value = '年龄不能为空';
    return;
  }
  if (!phone.value.trim()) {
    errorMessage.value = '手机号不能为空';
    return;
  }
  // 手机号格式验证（11位数字）
  if (!/^\d{11}$/.test(phone.value.trim())) {
    errorMessage.value = '手机号必须为11位数字';
    return;
  }
  
  if (password.value !== confirmPassword.value) {
    errorMessage.value = '两次输入的密码不一致';
    return
  }
  // 企业编码验证
  if (['管理员', '授权医护人员', '健康管理师'].includes(role.value)) {
    if (!enterpriseCode.value.trim()) {
      errorMessage.value = '请输入企业编码';
      return;
    }
    if (enterpriseCode.value.trim() !== 'hwadee') {
      errorMessage.value = '企业编码不正确';
      return;
    }
  }
  const registerData = {
    username: username.value,
    password: password.value,
    age: age.value,
    sex: sex.value,
    phone: phone.value,
    role: role.value,
    status: 'active',
    ...(['管理员', '授权医护人员', '健康管理师'].includes(role.value) ? { enterpriseCode: enterpriseCode.value } : {})
  };
  console.log('注册时发送的数据:', registerData);
  try {
    const response = await fetch('http://localhost:8080/api/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(registerData)
    });
    console.log('注册响应数据:', response);
    try {
      const data = await response.json();
      if (response.ok) {
        errorMessage.value = '注册成功'; setTimeout(() => errorMessage.value = '', 3000);
      } else {
        errorMessage.value = data.message;
      }
    } catch (parseError) {
      console.error('响应数据解析失败:', parseError);
      const text = await response.text();
      errorMessage.value = text;
    }
  } catch (error) {
    console.error('注册请求出错:', error);
    errorMessage.value = '注册请求出错，请稍后再试';
  }
}
</script>

<template>
  <div class="register-container">
    <div class="register">
      <h1>注册</h1>
      <div v-if="errorMessage" class="error-message">
        <span class="error-icon">⚠️</span>
        <span class="error-text">{{ errorMessage }}</span>
      </div>
      <input v-model="username" placeholder="用户名" />
      <input v-model="password" type="password" placeholder="密码" @input="validatePassword" />
        <div v-if="passwordErrorMessage" class="error-message">{{ passwordErrorMessage }}</div>
      <input v-model="confirmPassword" type="password" placeholder="确认密码" />
      <input v-model="age" placeholder="年龄" @input="validateAge" />
      <div v-if="ageErrorMessage" class="error-message">{{ ageErrorMessage }}</div>
      <div>
        <label>
          <input type="radio" v-model="sex" value="男" />
          男
        </label>
        <label>
          <input type="radio" v-model="sex" value="女" />
          女
        </label>
      </div>
      <input v-model="phone" placeholder="手机号" />
      <select v-model="role" style="margin-bottom: 15px;" @change="console.log('下拉框变化:', role)">
  <option value="用户">用户</option>
  <option value="管理员">管理员</option>
  <option value="授权医护人员">授权医护人员</option>
  <option value="健康管理师">健康管理师</option>
</select>

<div v-if="['管理员', '授权医护人员', '健康管理师'].includes(role)" style="border: 1px dashed #667eea; padding: 15px; border-radius: 8px; margin: 15px 0;">
  <div style="margin: 10px 0; color: #667eea; font-weight: 500;">企业编码</div>
  <input v-model="enterpriseCode" placeholder="企业编码" style="width: calc(100% - 24px); padding: 14px; margin: 8px 0; border: 1px solid #667eea; border-radius: 8px; font-size: 16px;" />
</div>
<button @click="handleRegister">注册</button>
      <RouterLink to="/login" class="back-to-login">返回登录</RouterLink>
    </div>
  </div>
</template>

<style scoped>
.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
  margin-bottom: 8px;
}
</style>

<style scoped>
.register-container {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0;
  font-family: 'Segoe UI', 'Arial', sans-serif;
}

.register {
  background: rgba(255, 255, 255, 0.95);
  .error-message {
    color: #d43f3a;
    background-color: #fff2f0;
    border: 1px solid #ffccc7;
    border-radius: 4px;
    padding: 10px 15px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    animation: fadeIn 0.3s ease-out;
  }
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.25);
  width: 100%;
  max-width: 400px;
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.register h1 {
  color: #333;
  text-align: center;
  margin-bottom: 35px;
  font-size: 24px;
  font-weight: 600;
}

.input-group {
  margin-bottom: 20px;
}

input,
select {
  width: calc(100% - 24px);
  padding: 14px;
  margin: 8px 0;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
}

input:focus,
select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}

.radio-group {
  display: flex;
  align-items: center;
  gap: 20px;
  margin: 10px 0;
}

input[type="radio"] {
  width: auto;
  margin-right: 8px;
}

label {
  color: #555;
  font-size: 16px;
}

button {
  width: 100%;
  padding: 14px;
  margin-top: 25px;
  background-color: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(102, 126, 234, 0.2);
}

button:hover {
  background-color: #5a67d8;
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(102, 126, 234, 0.3);
}

.back-to-login {
  display: block;
  margin-top: 20px;
  text-align: center;
  color: #667eea;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s ease;
}

.back-to-login:hover {
  color: #5a67d8;
  text-decoration: underline;
}
</style>
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-5px); }
  to { opacity: 1; transform: translateY(0); }
}